<template>
  <view class="chat-list-container">
    <view v-if="reconnecting" style="background:#fffbe6;color:#8c6d1f;padding:12rpx 20rpx;font-size:22rpx;border-bottom:1rpx solid #f0e6cc;display:flex;align-items:center;gap:12rpx;">
      <text>🔄</text>
      <text>实时服务连接中，部分功能暂不可用...</text>
    </view>
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          placeholder="搜索聊天记录..." 
          v-model="searchKeyword"
          @input="handleSearch"
        />
      </view>
      <button class="create-room-btn" @click="showCreateRoom = true">新建房间</button>
    </view>

    <!-- 创建房间弹窗 -->
    <view v-if="showCreateRoom" class="modal-overlay" @click="showCreateRoom = false">
      <view class="modal-container" @click.stop>
        <view class="modal-header">
          <text class="modal-title">创建房间</text>
          <button class="close-btn" @click="showCreateRoom = false">✕</button>
        </view>
        <view class="modal-content" style="padding: 24rpx; display: flex; flex-direction: column; gap: 16rpx;">
          <input class="input" placeholder="房间名称（可选）" v-model="createRoomForm.roomName" />
          <picker :range="roomTypeOptions" :value="createRoomTypeIndex" @change="onRoomTypeChange">
            <view class="picker-display">类型：{{ roomTypeOptions[createRoomTypeIndex] }}</view>
          </picker>
          <button class="submit-btn" @click="createRoom">创建</button>
        </view>
      </view>
    </view>

    <!-- 聊天列表 -->
    <view class="chat-list">
      <view 
        v-for="chat in filteredChats" 
        :key="chat.id"
        class="chat-item"
        @click="openChat(chat)"
      >
        <view class="chat-avatar">
          <image 
            v-if="chat.avatar" 
            :src="chat.avatar" 
            class="avatar-image"
            mode="aspectFill"
          />
          <text v-else class="avatar-text">{{ chat.name.charAt(0) }}</text>
          <view v-if="chat.isOnline" class="online-indicator"></view>
        </view>
        
        <view class="chat-content">
          <view class="chat-header">
            <text class="chat-name">{{ chat.name }}</text>
            <text class="chat-time">{{ formatTime(chat.lastMessageTime) }}</text>
          </view>
          <view class="chat-preview">
            <text class="preview-text">{{ chat.lastMessage }}</text>
            <view v-if="chat.unreadCount > 0" class="unread-badge">
              <text class="unread-count">{{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}</text>
            </view>
          </view>
        </view>
        
        <view class="chat-actions">
          <button class="action-btn" @click.stop="showChatOptions(chat)">⋯</button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredChats.length === 0" class="empty-state">
      <text class="empty-icon">💬</text>
      <text class="empty-text">{{ searchKeyword ? '没有找到相关聊天' : '暂无聊天记录' }}</text>
      <text class="empty-desc">{{ searchKeyword ? '尝试其他关键词' : '开始与好友聊天吧' }}</text>
    </view>

    <!-- 聊天选项弹窗 -->
    <view v-if="showChatOptionsModal" class="modal-overlay" @click="closeChatOptions">
      <view class="modal-container" @click.stop>
        <view class="modal-header">
          <text class="modal-title">聊天选项</text>
          <button class="close-btn" @click="closeChatOptions">✕</button>
        </view>
        <view class="modal-content">
          <view class="option-item" @click="markAsRead">
            <text class="option-icon">✓</text>
            <text class="option-text">标记为已读</text>
          </view>
          <view class="option-item" @click="pinChat">
            <text class="option-icon">📌</text>
            <text class="option-text">{{ selectedChat?.isPinned ? '取消置顶' : '置顶聊天' }}</text>
          </view>
          <view class="option-item" @click="muteChat">
            <text class="option-icon">🔇</text>
            <text class="option-text">{{ selectedChat?.isMuted ? '取消静音' : '静音' }}</text>
          </view>
          <view class="option-item danger" @click="deleteChat">
            <text class="option-icon">🗑️</text>
            <text class="option-text">删除聊天</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import chatService from '@/utils/websocket-chat-service.js'
export default {
  data() {
    return {
      searchKeyword: '',
      chats: [],
      reconnecting: false,
      showCreateRoom: false,
      roomTypeOptions: ['private', 'group'],
      createRoomTypeIndex: 0,
      createRoomForm: { roomName: '' },
      showChatOptionsModal: false,
      selectedChat: null
    }
  },
  
  computed: {
    filteredChats() {
      if (!this.searchKeyword) {
        // 按置顶和最后消息时间排序
        return this.chats.sort((a, b) => {
          if (a.isPinned && !b.isPinned) return -1
          if (!a.isPinned && b.isPinned) return 1
          return new Date(b.lastMessageTime) - new Date(a.lastMessageTime)
        })
      }
      
      const keyword = this.searchKeyword.toLowerCase()
      return this.chats.filter(chat => 
        chat.name.toLowerCase().includes(keyword) ||
        (chat.lastMessage || '').toLowerCase().includes(keyword)
      ).sort((a, b) => new Date(b.lastMessageTime) - new Date(a.lastMessageTime))
    }
  },
  
  onLoad() {
    this.loadChats()
    this.initWsBanner()
  },
  
  onShow() {
    this.loadChats()
  },
  
  methods: {
    async initWsBanner() {
      try {
        if (!chatService.isInitialized) {
          await chatService.init()
        }
        chatService.onStatusChange((info) => {
          if (info && info.status === 'reconnecting') this.reconnecting = true
          if (info && (info.status === 'connected' || info.status === 'disconnected' || info.status === 'error')) this.reconnecting = false
        })
      } catch (e) {}
    },
    // 加载聊天列表
    loadChats() {
      // 先从本地存储加载聊天列表（包含未读消息数量）
      this.loadChatsFromLocal();
      
      // 然后从服务器获取最新的房间列表
      this.loadChatsFromServer();
    },
    
    // 从本地存储加载聊天列表
    loadChatsFromLocal() {
      try {
        const chatListStr = uni.getStorageSync('chat_list');
        if (chatListStr) {
          const localChats = JSON.parse(chatListStr);
          if (Array.isArray(localChats) && localChats.length > 0) {
            this.chats = localChats;
            console.log('从本地加载聊天列表:', this.chats.length, '个聊天');
          }
        }
      } catch (error) {
        console.error('从本地加载聊天列表失败:', error);
      }
    },
    
    async loadChatsFromServer() {
      try {
        const currentUserStr = uni.getStorageSync('currentUser')
        if (!currentUserStr) return
        const currentUser = JSON.parse(currentUserStr)
        const userId = currentUser.id
        if (!userId) return
        const res = await apiService.getUserRooms(userId)
        if (res && res.code === 'SUCCESS' && Array.isArray(res.data)) {
          // 获取现有的本地聊天列表，用于保留未读消息数量等信息
          const existingChats = [...this.chats];
          
          // 将房间转换为聊天项，保留现有聊天的未读消息数量
          const updatedChats = res.data.map(room => {
            // 查找现有聊天
            const existingChat = existingChats.find(c => c.id === room.room_id);
            
            return {
              id: room.room_id,
              name: room.room_name || room.room_id,
              avatar: '',
              // 保留现有的最后消息和时间，如果没有则使用服务器提供的
              lastMessage: existingChat?.lastMessage || '',
              lastMessageTime: existingChat?.lastMessageTime || room.updated_at || new Date().toISOString(),
              // 保留未读消息数量
              unreadCount: existingChat?.unreadCount || 0,
              // 保留在线状态
              isOnline: existingChat?.isOnline || false,
              // 保留置顶和静音状态
              isPinned: existingChat?.isPinned || false,
              isMuted: existingChat?.isMuted || false
            };
          });
          
          // 更新聊天列表
          this.chats = updatedChats;
          
          // 保存到本地存储
          this.saveChats();
          
          console.log('从服务器加载聊天列表:', this.chats.length, '个聊天');
        }
      } catch (e) {
        console.error('从服务器加载房间失败:', e)
      }
    },
    
    // 保存聊天列表
    saveChats() {
      try {
        uni.setStorageSync('chat_list', JSON.stringify(this.chats))
      } catch (error) {
        console.error('保存聊天列表失败:', error)
      }
    },
    
    // 搜索处理
    handleSearch() {
      // 搜索逻辑已在computed中处理
    },
    
    // 打开聊天
    openChat(chat) {
      // 清除未读消息（本地展示）
      if (chat.unreadCount > 0) {
        chat.unreadCount = 0
        this.saveChats()
      }
      // 如果是私聊房间ID pm_{minId}_{maxId}，解析出对端ID作为 userId 传给聊天页
      let userIdParam = chat.id
      const m = /^pm_(\d+)_(\d+)$/.exec(chat.id)
      if (m) {
        const currentUserStr = uni.getStorageSync('currentUser')
        const currentUser = currentUserStr ? JSON.parse(currentUserStr) : null
        const myId = currentUser?.id
        const id1 = parseInt(m[1]), id2 = parseInt(m[2])
        const otherId = (myId === id1) ? id2 : id1
        userIdParam = otherId
      }
      uni.navigateTo({ url: `/pages/chat/chat?userId=${userIdParam}&userName=${chat.name}` })
    },
    
    // 显示聊天选项
    showChatOptions(chat) {
      this.selectedChat = chat
      this.showChatOptionsModal = true
    },
    
    // 关闭聊天选项
    closeChatOptions() {
      this.showChatOptionsModal = false
      this.selectedChat = null
    },
    
    // 标记为已读
    markAsRead() {
      if (this.selectedChat) {
        this.selectedChat.unreadCount = 0
        this.saveChats()
        uni.showToast({
          title: '已标记为已读',
          icon: 'success'
        })
      }
      this.closeChatOptions()
    },
    
    // 置顶聊天
    pinChat() {
      if (this.selectedChat) {
        this.selectedChat.isPinned = !this.selectedChat.isPinned
        this.saveChats()
        uni.showToast({
          title: this.selectedChat.isPinned ? '已置顶' : '已取消置顶',
          icon: 'success'
        })
      }
      this.closeChatOptions()
    },
    
    // 静音聊天
    muteChat() {
      if (this.selectedChat) {
        this.selectedChat.isMuted = !this.selectedChat.isMuted
        this.saveChats()
        uni.showToast({
          title: this.selectedChat.isMuted ? '已静音' : '已取消静音',
          icon: 'success'
        })
      }
      this.closeChatOptions()
    },
    
    // 删除聊天
    deleteChat() {
      if (!this.selectedChat) return
      
      uni.showModal({
        title: '删除聊天',
        content: `确定要删除与${this.selectedChat.name}的聊天记录吗？`,
        success: (res) => {
          if (res.confirm) {
            const index = this.chats.findIndex(chat => chat.id === this.selectedChat.id)
            if (index > -1) {
              this.chats.splice(index, 1)
              this.saveChats()
              uni.showToast({
                title: '聊天已删除',
                icon: 'success'
              })
            }
          }
        }
      })
      this.closeChatOptions()
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else if (diff < 7 * 86400000) { // 7天内
        return `${Math.floor(diff / 86400000)}天前`
      } else {
        return date.toLocaleDateString()
      }
    },
    onRoomTypeChange(e) {
      this.createRoomTypeIndex = Number(e.detail.value || 0)
    },
    async createRoom() {
      try {
        const currentUserStr = uni.getStorageSync('currentUser')
        if (!currentUserStr) return
        const currentUser = JSON.parse(currentUserStr)
        const userId = currentUser.id
        const roomType = this.roomTypeOptions[this.createRoomTypeIndex]
        const res = await apiService.createRoom({ userId, roomName: this.createRoomForm.roomName, roomType })
        if (res && res.code === 'SUCCESS') {
          this.showCreateRoom = false
          this.createRoomForm.roomName = ''
          await this.loadChatsFromServer()
          uni.showToast({ title: '创建成功', icon: 'success' })
        } else {
          throw new Error('创建失败')
        }
      } catch (e) {
        console.error('创建房间失败:', e)
        uni.showToast({ title: '创建失败', icon: 'error' })
      }
    }
  }
}
</script>

<style scoped>
.chat-list-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 搜索栏 */
.search-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.search-box {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 20rpx;
  padding: 16rpx 20rpx;
}

.search-icon {
  font-size: 28rpx;
  color: #999;
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  font-size: 24rpx;
  color: #333;
  border: none;
  background: transparent;
}

/* 聊天列表 */
.chat-list {
  background: white;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.chat-item:active {
  background: #f8f9fa;
}

.chat-item:last-child {
  border-bottom: none;
}

.chat-avatar {
  position: relative;
  margin-right: 16rpx;
}

.avatar-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.avatar-text {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.online-indicator {
  position: absolute;
  bottom: 2rpx;
  right: 2rpx;
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background: #4CAF50;
  border: 3rpx solid white;
}

.chat-content {
  flex: 1;
  min-width: 0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.chat-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-time {
  font-size: 20rpx;
  color: #999;
  margin-left: 12rpx;
}

.chat-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-text {
  font-size: 24rpx;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread-badge {
  background: #ff4757;
  color: white;
  border-radius: 12rpx;
  padding: 4rpx 8rpx;
  margin-left: 12rpx;
  min-width: 24rpx;
  text-align: center;
}

.unread-count {
  font-size: 18rpx;
  font-weight: bold;
}

.chat-actions {
  margin-left: 12rpx;
}

.action-btn {
  background: transparent;
  border: none;
  font-size: 24rpx;
  color: #999;
  padding: 8rpx;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
  color: #999;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  width: 90%;
  max-width: 500rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #e0e0e0;
}

.modal-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #e74c3c;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20rpx;
}

.modal-content {
  padding: 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.option-item:last-child {
  border-bottom: none;
}

.option-item:active {
  background: #f8f9fa;
}

.option-item.danger {
  color: #ff4757;
}

.option-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
}

.option-text {
  font-size: 28rpx;
  color: inherit;
}
.create-room-btn {
  margin-top: 12rpx;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 12rpx 20rpx;
  font-size: 24rpx;
}
.input { border: 1rpx solid #e0e0e0; border-radius: 8rpx; padding: 12rpx; font-size: 24rpx; }
.picker-display { padding: 12rpx; background: #f8f9fa; border-radius: 8rpx; font-size: 24rpx; }
.submit-btn { background: #4caf50; color: #fff; border: none; border-radius: 8rpx; padding: 12rpx 20rpx; font-size: 24rpx; }
</style>
